package Texas;


import java.util.*;

public class PlayerIterator implements Iterator<Player>{
	private ArrayList<Player> _players;
	private Player _prePlayer;
	private Player _currentPlayer;
	private int _counter;
	
	public PlayerIterator(ArrayList<Player> players, DealerButton dealerButton) {
		_players = players;
		_counter = _players.size();
		_currentPlayer = getFirstPlayer(dealerButton);
	}

	@Override
	public boolean hasNext() {
		Player player;
		
		if(_prePlayer != null) {
			if(_prePlayer.hasRaised()) {
				_prePlayer.clearStates();
				_counter = _players.size()-1;
			}
			for (int i = 0; i < _players.size(); i++) {
				player = _players.get((_players.indexOf(_prePlayer)+(i+1))%_players.size());
				if(!player.hasFolded()) {
					_currentPlayer = player;
					break;
				}
				_counter--;
			}
		}
		if(_counter > 0)
			return true;
		return false;
	}	
	
	@Override
	public Player next() {
		/*if(_prePlayer != null && _prePlayer.hasRaised()) {			
			if(!_prePlayer.hasFolded()) {
				_prePlayer.clearStates();
			}
			_counter = _players.size()-1;
		}*/
		
		_counter--;
		_prePlayer = _currentPlayer;
		return _currentPlayer;
	}

	@Override
	public void remove() {
	}
	
	private Player getFirstPlayer(DealerButton dealerButton) {
		Player player;
		
		for (int i = 0; i < _players.size(); i++) {
			player = _players.get((_players.indexOf(dealerButton.getPlayer())+(i+3))%_players.size());
			if(!player.hasFolded()) {
				return player;
			}
			_counter--;
		}
		
		return null;
	}
}
